<template>
	<view class="page pb-safe-area">
		<view class="p-4 flex flex-column grid-gap-2" v-if="showLocation">
			<view class="pinyin_prefix h10 font-weight-600">当前定位城市</view>
			<view class="flex flex-x-flex-start">
				<view class="bg-white rounded-2 p-2 flex flex-center h9 font-weight-600 min-w-3" v-if="locationLoading === 'loading'">定位中...</view>
				<view class="bg-white rounded-2 p-2 flex flex-center h9 font-weight-600 min-w-30" v-else-if="locationLoading === 'success'" @tap="selected(location)">{{
					location.title }}</view>
				<view class="bg-white rounded-2 p-2 flex flex-center h9 font-weight-600 min-w-3" v-else-if="locationLoading === 'empty'">{{ city }} 暂未开通</view>
				<view class="bg-white rounded-2 p-2 flex flex-center h9 font-weight-600 min-w-3" v-else @tap="getLocation">定位失败，点击重试</view>
			</view>
		</view>
		<view class="p-4 flex flex-column grid-gap-2" v-for="(data, pinyin_prefix) in regions" :key="pinyin_prefix">
			<text class="pinyin_prefix h10 font-weight-600">{{ pinyin_prefix }}</text>
			<view class="grid-columns-6  grid-gap-2">
				<view class="grid-column-2 bg-white rounded-2 p-2 flex flex-center h9 font-weight-600" v-for="item in data" :key="item.id" @tap="selected(item)">
					{{ item.title }}</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, nextTick,onBeforeUnmount } from 'vue';
import { useMap } from "@/utils/map";
import { useStorage, $api, $message, $page } from "@/utils";
import { $EventName } from "@/utils/const/env";
import { onLoad } from '@dcloudio/uni-app';
let map: any;
const showLocation = ref(false);
const locationLoading = ref('loading');
const location = ref({});
const regions = ref([]);
const city = ref('');
const event = ref('');
const useInitMap = () => {
	map = useMap(() => {
		nextTick(() => {
			showLocation.value = true;
			if (city) {
				getLocation();
			}
		});
	});
}
onLoad((options: any) => {
	if (options.event) {
		event.value = options.event;
	}
	const storage = useStorage();
	const city = storage.get('city');
	if (city) {
		regions.value = city;
	}
	useInitMap();
	uni.$once($EventName.WEBCONFIG_READY, useInitMap)
	$api.Regions.getRegions().then((data: any) => {
		const regionsData=serializeData(data);
		const sortedKeys = Object.keys(regionsData).sort();
		let sortedObj:any = {};
		sortedKeys.forEach(key => {
			sortedObj[key] = regionsData[key];
		});
		regions.value = sortedObj;
		if (!city) {
			getLocation();
		}
		storage.set('city', regions.value);
	}).catch((err: any) => {
		$message.error(err.msg);
	});
});
onBeforeUnmount(() => {
	uni.$off($EventName.WEBCONFIG_READY, useInitMap);
});
const getLocation = () => {
	if (!map.isReady()) { return; }
	locationLoading.value = 'loading';
	map.getCurrentPosition({ isHighAccuracy: false }).then((result: any) => {
		// #ifdef H5
		map.getAddress([result.position.lng, result.position.lat]).then((result: any) => {
			locationLoading.value = 'success';
			city.value = result.addressComponent.province;
			if(result.addressComponent.city){
				city.value =result.addressComponent.city;
			}
			findCity();
		}).catch((err: any) => {
			locationLoading.value = 'fail';
			console.log(err);
		})
		// #endif
		// #ifdef APP
		locationLoading.value = 'success';
		city.value = result.address.province;
		if(result.address.city){
			city.value = result.address.city;
		}
		findCity();
		// #endif
        // #ifdef MP-WEIXIN
		locationLoading.value = 'success';
		city.value = result.regeocodeData.addressComponent.province
		if(result.regeocodeData.addressComponent.city.length>0){
			city.value = result.regeocodeData.addressComponent.city;
		}
		findCity();
        // #endif
	}).catch(() => {
		locationLoading.value = 'fail';
	});
}
const findCity = () => {
	for (const pinyin_prefix in regions.value) {
		if (Object.hasOwnProperty.call(regions.value, pinyin_prefix)) {
			const cityData = regions.value[pinyin_prefix];
			for (let i = 0; i < cityData.length; i++) {
				const item = cityData[i];
				if (item.title.includes(city.value)) {
					location.value = item;
					return;
				}
			}
		}
	}
	if (!location.value.id) {
		locationLoading.value = 'empty';
	}
}
const serializeData = (data: any): any => {
	let d: any = {};
	for (let i = 0; i < data.length; i++) {
		const province = data[i];
		if (province.children) {
			if (province.children.length > 1 || data.length > 1) {
				for (let j = 0; j < province.children.length; j++) {
					const city: any = province.children[j];
					if (!d[city.pinyin_prefix]) {
						d[city.pinyin_prefix] = [];
					}
					d[city.pinyin_prefix].push({
						id: city.id,
						title: city.title,
						level: city.level
					});
				}
			} else if (data.length === 1) {
				return serializeData(province.children);
			}
		}
	}
	return d;
}
const selected = (e: any) => {
	if (event.value) {
		uni.$emit(event.value, e);
		$page.back();
	}
}
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
}

.pinyin_prefix {
	// 大写
	text-transform: uppercase;
}
</style>
